package com.mrjy.queries.bo;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrjy.common.dto.QuestionCommentDto;
import com.mrjy.common.dto.QuestionDto;
import com.mrjy.common.entity.HappinessInfo;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.QuestionComment;
import com.mrjy.common.entity.QuestionInfo;
import com.mrjy.common.entity.QuestionTypeRel;
import com.mrjy.common.entity.RecordInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.StageInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.entity.VideoType;
import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.exception.InnerException;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.common.util.SolrUtil;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.util.HappinessInfoEnum;
import com.mrjy.integral.util.HappinessInfoUtil;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IRecordIncomeInfoDao;
import com.mrjy.maintain.dao.IRecordInfoDao;
import com.mrjy.maintain.dao.IStageInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.queries.dao.IQuestionCommentDao;
import com.mrjy.queries.dao.IQuestionInfoDao;
import com.mrjy.queries.dao.IQuestionTypeRelDao;
import com.mrjy.queries.dto.MiniMyQAQDTO;
import com.mrjy.queries.dto.QuestionInfoDTO;
import com.mrjy.queries.util.QuestionCommentDtoComparator;

@Service("QuestionInfoBo")
public class QuestionInfoBo implements IQuestionInfoBo {
	@Resource
	private IQuestionInfoDao questionInfoDao;
	@Resource
	private IQuestionCommentDao questionCommentDao;
	@Resource
	private IUserInfoDao userInfodao;
	@Resource
	private IStageInfoDao stageDao;
    @Resource
    private IUserBalancePaymentDao userBalancePaymentDao;
    @Resource
    private IRecordIncomeInfoDao recordIncomeInfoDao;
    @Resource
    private IMessageInfoDao messageInfoDao;
    @Resource
    private IQuestionTypeRelDao questionTypeRelDao;
    @Resource
	private IUserMemberInfoDao userMemberInfoDao;
    
    @Resource
	private IHappinessInfoDao happinessInfoDao;
    @Resource
	private SolrServerClient solrServerClient;
    @Resource
   	private IRecordInfoDao recordInfoDao;
    
    private Logger LOGGER = LoggerFactory.getLogger(QuestionInfoBo.class);
    
    @Override
    public List<QuestionInfo> queryQuestionInfosByPage(UserInfo userInfo,
			QuestionDto questionDto) {
		if (userInfo == null) {
			return new ArrayList<QuestionInfo>();
		}
		QuestionInfo questionInfo = new QuestionInfo();
		switch (questionDto.getStage()) {
			case "婴儿":
				questionInfo.setTypeId(1);
				break;
			
			case "幼儿":
				questionInfo.setTypeId(2);
				break;
			
			case "小学":
				questionInfo.setTypeId(3);
				break;
			
			case "初中":
				questionInfo.setTypeId(4);
				break;
				
			case "高中":
				questionInfo.setTypeId(5);
				break;
				
			case "大学":
				questionInfo.setTypeId(6);
				break;
			default:
				break;
		}
		questionInfo.setUserId(userInfo.getId());
		questionInfo.setPage(questionDto.getPage());
		questionInfo.setRows(questionDto.getRows());
		List<QuestionInfo> list = null;
		if ("new".equals(questionDto.getFilter())) {
			list = questionInfoDao.queryQuestionListByTime(questionInfo);
		}else if("hot".equals(questionDto.getFilter())) {
			list = questionInfoDao.queryQuestionListByHot(questionInfo);
		}else {
			return null;
		}
		long now = new Date().getTime();
		long qt = 0;//时间差
		for (QuestionInfo q : list) {
			qt = (now - q.getQuestionTime().getTime())/1000;
			if (qt < 60) {
				q.setQuestionTimeString(qt +"秒前");
			}else if ((qt /= 60) < 60 ) {
				q.setQuestionTimeString(qt +"分钟前");
			}else if ((qt /= 60) < 24) {
				q.setQuestionTimeString(qt +"小时前");
			}else if ((qt /= 24) < 5) {
				q.setQuestionTimeString(qt +"天前");
			}else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				q.setQuestionTimeString(sdf.format(q.getQuestionTime()));
			}
			if (StringUtils.isNotBlank(q.getImgArr())) {
				q.setImgArray(q.getImgArr().split(","));
				q.setImgArr(null);
			}
		}
		return list;
	}
	
	@Override
	public QuestionInfo queryQuestionById(int id, UserInfo userInfo) {
		if (userInfo == null) {
			return null;
		}
		QuestionInfo q = new QuestionInfo();
		q.setId(id);
		q.setUserId(userInfo.getId());
		q.setDisableFlag(0);
		QuestionInfo questionInfo = questionInfoDao.queryById(q);
		if (questionInfo != null) {
			long now = new Date().getTime();
			long qt = 0;//时间差
			qt = (now - questionInfo.getQuestionTime().getTime())/1000;

            //时间分钟间隔
            questionInfo.setIsOverThreeDay((int) (qt / 60));
            if (qt < 60) {
                questionInfo.setQuestionTimeString(qt +"秒前");
			}else if ((qt /= 60) < 60 ) {
				questionInfo.setQuestionTimeString(qt +"分钟前");
			}else if ((qt /= 60) < 24) {
				questionInfo.setQuestionTimeString(qt +"小时前");
			}else if ((qt /= 24) < 5) {
				questionInfo.setQuestionTimeString(qt +"天前");
			}else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				questionInfo.setQuestionTimeString(sdf.format(questionInfo.getQuestionTime()));
			}
			if (StringUtils.isNotBlank(questionInfo.getImgArr())) {
				questionInfo.setImgArray(questionInfo.getImgArr().split(","));
				questionInfo.setImgArr(null);
			}
		}
		return questionInfo;
	}
	
	@Override
	public List<QuestionInfo> queryMyQuestionInfos(QuestionDto questionDto,
			UserInfo userInfo) {
		if (userInfo == null) {
			return new ArrayList<QuestionInfo>();
		}

		QuestionInfo questionInfo = new QuestionInfo();
		questionInfo.setPage(questionDto.getPage());
		questionInfo.setRows(questionDto.getRows());
		questionInfo.setUserId(userInfo.getId());//
		questionInfo.setId(userInfo.getId());//用id代替userId查询个人的问题列表
		List<QuestionInfo> questionInfos = questionInfoDao.queryQuestionListByTime(questionInfo);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm");
		for (QuestionInfo q : questionInfos) {
			q.setQuestionTimeString(simpleDateFormat.format(q.getQuestionTime()));
			if (StringUtils.isNotBlank(q.getImgArr())) {
				q.setImgArray(q.getImgArr().split(","));
				q.setImgArr(null);
			}
		}
		return questionInfos;
	}
	
	@Override
	public String insert(QuestionInfo questionInfo,UserInfo userInfo) {
		if (userInfo == null) {
			return "userInfo_error";
		}
		if (StringUtils.isBlank(questionInfo.getQuestionContent())) {
			return "error";
		}else {
			String stage = questionInfo.getTypeName();
			switch (stage) {
				case "婴儿":
					questionInfo.setTypeId(1);
					break;
				case "幼儿":
					questionInfo.setTypeId(2);
					break;
				
				case "小学":
					questionInfo.setTypeId(3);
					break;
				
				case "初中":
					questionInfo.setTypeId(4);
					break;
					
				case "高中":
					questionInfo.setTypeId(5);
					break;
					
				case "大学":
					questionInfo.setTypeId(6);
					break;
				default:
					break;
			}
			questionInfo.setUserId(userInfo.getId());
			questionInfo.setGoodNum(0);
			questionInfo.setCommentNum(0);
			questionInfo.setPriority(0);
			questionInfo.setDisableFlag(0);
			questionInfo.setQuestionTime(new Date());
			
			questionInfoDao.insert(questionInfo);
			return "ok";
		}
	}
	
	
	
	@Override
	public String insertBack(QuestionInfo questionInfo, UserInfo userInfo) {
		if (userInfo == null) {
			return "error";
		}
		
		
		
		
		return null;
	}

	@Override
	public Map<String, Object> queryQuestionInfosBack(QuestionInfo question,UserInfo userInfo) {
		if (StringUtils.isNotBlank(question.getQuestionContent())) {
			question.setQuestionContent("%"+question.getQuestionContent() + "%");
		}
		if (question.getTypeId() == null) {
			question.setTypeId(0);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		if (StringUtils.isNotBlank(question.getStartTime())) {
//			try {
//				question.setStartDate(sdf.parse(question.getStartTime()).getTime()/1000);
//			} catch (ParseException e) {
////				e.printStackTrace();
//			}
//		}
//		if (StringUtils.isNotBlank(question.getEndTime())) {
//			try {
//				question.setEndDate(sdf.parse(question.getEndTime()).getTime()/1000+86400);
//			} catch (ParseException e) {
////				e.printStackTrace();
//			}
//		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", questionInfoDao.countQuestionInfo(question));
		List<QuestionInfo> list = questionInfoDao.queryQuestionListBack(question);	
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (QuestionInfo q : list) {
			q.setQuestionTimeString(simpleDateFormat.format(q.getQuestionTime()));
			if (StringUtils.isNotBlank(q.getImgArr())) {
				q.setImgArray(q.getImgArr().split(","));
				q.setImgArr(null);
			}
		}
		map.put("rows",list);
		return map;
	}
	
	@Override
	public Object txUpdateDisableFlag(QuestionInfo question,UserInfo userInfo) {
		Map<String, Object> map = new HashMap<String, Object>();	
		if (userInfo==null) {
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (question.getIds()==null||question.getIds().length==0) {
			map.put("err_code", 400);
			map.put("err_msg", "请勾选要操作的记录");
			return map;
		}
		int row = questionInfoDao.updateDisableFlag(question);
		if (row>0) {
			if (question.getDisableFlag().intValue() == 0) {
				//数据库启用,添加索引(提问+回答)
				try {
					//添加提问索引 
					QuestionInfo info = null;
					QuestionComment comment =null;
					RecordInfo recordInfo = null;
					for (Integer id : question.getIds()) {
						SolrEntity questionEntity = new SolrEntity();
						info = new QuestionInfo();
						info.setId(id);
						question = questionInfoDao.queryById(info);
						questionEntity.setId("question_"+id);
						questionEntity.setQuestionId(id);
						questionEntity.setQuestionContent(question==null?"":question.getQuestionContent());
						questionEntity.setQuestionDesc(question==null?"":question.getQuestionDesc());
						questionEntity.setQuestionTypes(question==null?null:question.getTypeName());
		                solrServerClient.add(questionEntity);
		                //如果该提问有回答,还要添加回答索引
		                comment = new QuestionComment();
		                comment.setQuestionId(id);
		                List<QuestionComment> comList = questionCommentDao.selectCommentByQuestionId(comment);
		                for (QuestionComment questionComment : comList) {
		                	SolrEntity commentEntity = new SolrEntity();
		                	//用commentId去语音表查,看是否属于语音回答
		                	recordInfo = recordInfoDao.queryByCommentId(questionComment.getId());
		                	if (recordInfo != null) {
		                		//语音回答
		                		commentEntity.setRecordName(recordInfo.getRecordName());
		                		commentEntity.setRecordDuration(recordInfo.getDuration()+"");
		                	}else {
		                		//文字回答
		                		commentEntity.setCommentContent(questionComment.getCommentContent());
		                	}
		                	commentEntity.setId("questionComment_"+questionComment.getId());
		                	commentEntity.setCommentId(questionComment.getId());
		                	commentEntity.setQuestionId(questionComment.getQuestionId());
		                	commentEntity.setQuestionContent(questionComment.getQuestionContent());
		                	UserInfo commentUser = userInfodao.queryByIdForBack(questionComment.getUserId());
		                	commentEntity.setUserId(questionComment.getUserId());
		                	commentEntity.setHeadImgUrl(commentUser.getHeadImgUrl());
		                	commentEntity.setPicName(commentUser.getPicName());
		                	solrServerClient.add(commentEntity);
		                }
					}
					map.put("solr_msg", "索引添加成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引添加失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}else if (question.getDisableFlag().intValue() == 1) {
				//数据库禁用,要删除索引(提问+回答)
				try {
                	//删除提问索引 
					QuestionComment comment = null;
					for (Integer id : question.getIds()) {
						solrServerClient.deleteById("question_"+id);
						//如果该提问有回答,还要删除回答索引
						comment = new QuestionComment();
						comment.setQuestionId(id);
						List<QuestionComment> comList = questionCommentDao.selectCommentByQuestionId(comment);
						for (QuestionComment questionComment : comList) {
							solrServerClient.deleteById("questionComment_"+questionComment.getId());
						}
					}
					map.put("solr_msg", "索引删除成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引删除失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
		return map;
	}
	
	@Override
	public Object txUpdateStickStatus(Integer questionId,String isStick, HttpSession session) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
			return ResultUtil.error(ResultEnum.NOT_LOGIN);
		}
        if (null == questionId || null == isStick) {
        	return ResultUtil.error(ResultEnum.PARAM_ERROR);
		}
        QuestionInfo question = new QuestionInfo();
        question.setId(questionId);
        question = questionInfoDao.queryById(question);
        if (null == question) {
        	LOGGER.error("【置顶帖子】查询不到该帖子,questionId={}",questionId);
        	throw new InnerException(ResultEnum.POST_NOT_EXIST);
		}
        question.setIsStick(isStick);
        question.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        questionInfoDao.updateById(question);
		return ResultUtil.success();
	}
	
	@Override
	public Object getStageList(UserInfo userInfo) {
		StageInfo stageInfo = new StageInfo();
		stageInfo.setId(0);
		stageInfo.setText("全部");
		List<StageInfo> sList = stageDao.queryList(stageInfo);
		for (StageInfo s : sList) {
			s.setText(s.getStageName());
		}
		sList.add(0, stageInfo);
		return sList;
	}

	@Override
	public Object txUpdateById(QuestionInfo question,HashMap<String, Object> map) {
		if(null == question.getId() || "".equals(question.getId())){
			map.put("err_code", -2);
			map.put("err_msg", "问题ID不存在");
			return map;
		}
		if(null == question.getTypeIds()){
			map.put("err_code", 400);
			map.put("err_msg", "问题标签不能为空");
			return map;
		}
		if(question.getTypeIds().length>10){
			map.put("err_code", 401);
			map.put("err_msg", "问题标签不能超过10个");
			return map;
		}
		//更新中间表
		Integer[] typeIds = question.getTypeIds();
		QuestionTypeRel r = new QuestionTypeRel();
		r.setQuestionId(question.getId());
		questionTypeRelDao.deleteByQuestionId(r); //先删除 
		for (Integer i : typeIds) {
			QuestionTypeRel rel = new QuestionTypeRel();
			rel.setQuestionId(question.getId());
			rel.setTypeId(i);
			questionTypeRelDao.insert(rel); //再添加
		}
		
		int result = questionInfoDao.updateById(question);
		if(result == 1){
			
			//编辑免费提问才更新solr(付费提问以回答的形式存在solr中)
			if (questionInfoDao.queryById(question).getInvitedPersonId() == null) {
                try {
                	//更新提问索引 
                	SolrEntity entity = new SolrEntity();
                	entity.setId("question_"+question.getId());
                	entity.setQuestionId(question.getId());
                	entity.setQuestionContent(question.getQuestionContent());
                	entity.setQuestionDesc(question.getQuestionDesc());
                	entity.setQuestionTypes(SolrUtil.formatVideoTypes(question.getTypeIds()));
                	solrServerClient.add(entity);
                	
                	//如果该提问有回答,还要更新回答索引
                	QuestionComment comment = new QuestionComment();
                	comment.setQuestionId(question.getId());
                	List<QuestionComment> comList = questionCommentDao.selectCommentByQuestionId(comment);
                	for (QuestionComment questionComment : comList) {
                		SolrInputDocument document = new SolrInputDocument();
                		document.addField("id", "questionComment_"+questionComment.getId());
                		Map<String, String > operation = new HashMap<>();
                		operation.put("set", question.getQuestionContent());
                		document.addField("questionContent", operation);
                		solrServerClient.addDoc(document);
                	}
					map.put("solr_msg", "索引更新成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引更新失败]："+e.getMessage());
					map.put("solr_msg", "索引更新失败");
					map.put("err_code", 2);
		            map.put("err_msg", "提问更新失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "提问更新成功");
			return map;
		}else{
			map.put("err_code", 500);
			map.put("err_msg", "提问更新失败");
			return map;
		}
	}

	@Override
	public int deleteByIds(int[] ids) {
		// TODO Auto-generated method stub
		try{
			return questionInfoDao.deleteByIds(ids);
		}catch(DataAccessException  e){
			return 0;
		}
	}

	@Override
	public Object getPageQuestionByContent(QuestionInfo question) {
		Map<String,Object> map = new HashMap<String, Object>();
		Map result = questionInfoDao.countPageQuestionByContent(question);
        Object count = result.get("count");
        if (count==null){
            map.put("err_msg","error");
            return map;
        }
        int total=Integer.parseInt(count.toString());
        if(total > 0){
			List<QuestionInfo> list = questionInfoDao.getPageQuestionByContent(question);
			map.put("rows", list);
		}
		map.put("total", total);
		return map;
	}


    @Override
    public Object selectById(QuestionInfo info) {
    	Map<String, Object> map = new HashMap<>();
        if (null == info || null == info.getId()) {
            return ResultUtil.error(ResultEnum.PARAM_ERROR);
        }
        QuestionInfo questionInfo = questionInfoDao.selectById(info.getId());
        if (null == questionInfo) {
			return ResultUtil.error(ResultEnum.POST_NOT_EXIST);
		}
        List<VideoType> typeList = questionTypeRelDao.queryByQuestionId(info.getId());
        if (questionInfo.getInvitedPersonId() != null) {
            QuestionComment questionComment = new QuestionComment();
            questionComment.setQuestionId(questionInfo.getId());
            questionComment.setUserId(questionInfo.getInvitedPersonId());
            QuestionComment questionComment1 = questionCommentDao.queryCommentByQid(questionComment);

            if (questionComment1 != null) {
                map.put("isNeedPrivilege", questionComment1.getIsNeedPrivilege());
            } else {
                map.put("isNeedPrivilege", -1);
            }
        }

		if ( questionInfo.getQuestionTime() != null) {
			long now = new Date().getTime();
			long qt = 0;//时间差
			qt = (now - questionInfo.getQuestionTime().getTime())/1000;
            int gapTime = (int) (qt / 60);
            questionInfo.setGapTime(gapTime);
            if (qt < 60) {
                questionInfo.setQuestionTimeString("刚刚");
			}else if ((qt /= 60) < 60 ) {
				questionInfo.setQuestionTimeString(qt +"分钟前");
			}else if ((qt /= 60) < 24) {
				questionInfo.setQuestionTimeString(qt +"小时前");
			}else if ((qt /= 24) < 5) {
				questionInfo.setQuestionTimeString(qt +"天前");
			}else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				questionInfo.setQuestionTimeString(sdf.format(questionInfo.getQuestionTime()));
			}

            if (questionInfo.getInvitedPersonId() != null && gapTime > 3 * 24 * 60) {
                questionInfo.setIsOverThreeDay(1);//已经超过了三天
            }
        }
        map.put("err_code", 0);
		map.put("err_msg", "查询成功");
		map.put("questionInfo", questionInfo);
		map.put("typeList", typeList);
		return map;
	}
    
	@Override
	public Object queryPageNewestQuestion(QuestionInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<QuestionInfo> list = questionInfoDao.queryPageNewestQuestion(info);
		int total = questionInfoDao.countNewestQuestion(info);
		if(null != list && list.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
			map.put("rows", null);
		}
		map.put("total", total);
		return map;
	}
	@Override
	public Object queryMyQuestionByUserId(QuestionInfo info) {
		// TODO Auto-generated method stub
		Map<String,Object> map = new HashMap<String, Object>();
		List<QuestionInfo> list = questionInfoDao.queryMyQuestionByUserId(info);
        int total = questionInfoDao.countMyQuestionByUserId(info);
        if(null != list && list.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
			map.put("rows", null);
		}
        map.put("total", total);
		return map;
	}

	@Override
    public Object txInsertQuestion(QuestionInfo info, Map<String, Object> map) {
        info.setQuestionTime(new Date());
        if (null == info.getIsAnonymous()) {
            info.setIsAnonymous(1);
        }
        if (null == info.getQuestionViewNum()) {
			info.setQuestionViewNum(0);
		}
		if (null == info.getCommentNum()) {
			info.setCommentNum(0);
		}
		if (null == info.getGoodNum()) {
			info.setGoodNum(0);
		}

        if (info.getInvitedPersonId() != null) {
            info.setDisableFlag(1);
        } else {
            info.setDisableFlag(0);
        }
        int result = questionInfoDao.insertAndGetId(info);
        if (result > 0) {
        	QuestionTypeRel rel = new QuestionTypeRel();
        	rel.setQuestionId(info.getId());
        	if(info.getTypeIds() != null && info.getTypeIds().length > 0 ){
        		for(int i =0;i<info.getTypeIds().length;i++){
            		rel.setTypeId(info.getTypeIds()[i]);
            		int rows = questionTypeRelDao.insert(rel);
            		if(rows<0){
            			map.put("type-msg", "插入问题type失败");
            		}
            	}
        	}
            if (info.getDisableFlag() == 0) {
                //积分添加
                IntegralInfo integral = IntegralUtil.setIntegral(info.getUserId()
                        , IntegralEnum.ASK.getScore()
                        , IntegralEnum.ASK.getTypeDesc()
                        , IntegralEnum.ASK.getTypeId()
                        , info.getId());

                map.put("score", integral.getScore());
                //爱值添加
                HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(info.getUserId()
                        , HappinessInfoEnum.ASK.getLoveValue(), HappinessInfoEnum.ASK.getTypeDesc()
                        , HappinessInfoEnum.ASK.getTypeId(), "0", info.getId());
                happinessInfoDao.insert(hi);
                
                //添加索引(免费提问添加索引,付费提问等到讲师回答后再添加)
                SolrEntity entity = new SolrEntity();
                entity.setId("question_"+info.getId());
                entity.setQuestionId(info.getId());
                entity.setQuestionContent(info.getQuestionContent());
                entity.setQuestionDesc(info.getQuestionDesc());
                entity.setQuestionTypes(SolrUtil.formatVideoTypes(info.getTypeIds()));
                try {
					solrServerClient.add(entity);
					map.put("solr_msg", "索引插入成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引插入失败]："+e.getMessage());
					map.put("solr_msg", "索引插入失败");
					map.put("err_code", 2);
		            map.put("err_msg", "插入失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
            }
            map.put("err_code", 0);
            map.put("err_msg", "插入成功");
            map.put("question_id", info.getId());
        }else {
        	map.put("err_code", 2);
            map.put("err_msg", "插入失败");
		}
        return map;
    }

	@Override
    public Object queryMyQAPageByUserId(QuestionInfo info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        UserMemberInfo userMemberInfo = null;
        //get userId
        if (userInfo != null) {
            info.setGoodUserId(userInfo.getId());
            if (info.getUserId().equals(userInfo.getId())) {
                info.setIsAnonymous(null);
            }

            userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo.getId());
        } else {
            info.setIsAnonymous(1);
        }
        
        PageHelper.startPage(info.getPage(), info.getRows());
        List<QuestionCommentDto> list = questionInfoDao.queryMyQAPageByUserId(info);
        PageInfo<QuestionCommentDto> pageInfo = new PageInfo<>(list);
        map.put("total",pageInfo.getTotal());

        dealListenAuth(info, list, userMemberInfo);
        if (null != list && list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("rows", null);
		}
		return map;
	}

	@Override
	public Object queryPageByViewNum(QuestionInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<QuestionInfo> list = questionInfoDao.queryPageByViewNum(info);
		int total = questionInfoDao.countByTypeId(info);
		if (null != list && list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
			map.put("total", total);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("total", total);
		}
		return map;
	}

	@Override
	public Object txAddQuestionViewNum(Integer qid) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = questionInfoDao.addQuestionViewNum(qid);
		if (count > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "更新视频浏览量成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新视频浏览量失败");
		}
		return map;
	}

	@Override
	public Object queryExistQuestionByTopicId(QuestionInfo info,
			HashMap<String, Object> map) {
		if(null == info.getTypeId() || "".equals(info.getTypeId())){
			map.put("err_code", -2);
			map.put("err_msg", "出入话题ID为空");
			return map;
		}
		QuestionInfo existInfo = questionInfoDao.queryExistQuestionByTopicId(info);
		if(null == existInfo){
			map.put("err_code", 1);
			map.put("err_msg", "可以提问");
			return map;
		}else{
			map.put("err_code", 0);
			map.put("err_msg", "编辑提问");
			map.put("info", existInfo);
			return map;
		}
	}

	@Override
	public Object selectQuestionListPage(QuestionInfo info,HttpSession session) {
		Map<String,Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (null == info) {
			map.put("err_code", 400);
			map.put("err_msg", "参数异常");
			return map;
		}
		
		int total = questionInfoDao.countQuestionInfo(info);
		QuestionInfo temp = new QuestionInfo();
		if(total > 0){
			List<QuestionInfo> list = questionInfoDao.selectQuestionListPage(info);
			if (null != list && list.size() > 0) {
				//List<QuestionInfo> resultList = new ArrayList<QuestionInfo>();
				for (QuestionInfo questionInfo : list) {
					questionInfo.setQuestionTimeString(DateUtil.longToString(questionInfo.getQuestionTime().getTime(), DateUtil.FULL_DATE));
					//resultList.add(questionInfo);
				}
                map.put("totalQuestion", total); //全站提问数
                map.put("err_code", 0);
					map.put("err_msg", "查询成功");
					map.put("rows", list);
					map.put("total", total);
				}else {
                map.put("totalQuestion", total); //全站提问数
                map.put("err_code", 1);
					map.put("er_msg", "无数据");
					map.put("total", total);
					map.put("rows", list);
				}
			}else {
            map.put("totalQuestion", total); //全站提问数
            map.put("err_code", 1);
				map.put("er_msg", "无数据");
				map.put("total", total);
				map.put("rows", null);
			}
			return map;
		}

		@Override
		public Object selectUserById(int id) {
			// TODO Auto-generated method stub
			Map<String,Object> map = new HashMap<String, Object>();
			UserInfo user = userInfodao.selectUserById(id);
			if(user!=null){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("user", user);
			}else{
				map.put("err_code", -1);
				map.put("err_msg", "查询失败");
				map.put("user", null);
			}
			return map;
		}


    @Override
    public Object dispatcherQuestion(QuestionInfo info) {
        Map<String,Object> map = new HashMap<String, Object>();
        UserInfo user=null;
        //UserInfo user = userInfodao.selectUserById(id);
        if(user!=null){
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("user", user);
        }else{
            map.put("err_code", -1);
            map.put("err_msg", "查询失败");
            map.put("user", null);
        }
        return map;
    }

    @Override
	public Object queryFamilyQuestionUserInfoForPC(QuestionInfo info) {
		Map<String,Object> map = new HashMap<String, Object>();
		List<QuestionInfo> list = questionInfoDao.queryFamilyQuestionUserInfoForPC(info);
		if (null != list && list.size() > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("er_msg", "无数据");
			map.put("rows", list);
		}
		return map;
	}

	@Override
    public Object queryPageNewestQuestionComment(QuestionInfo info, HttpSession session) {
        // TODO Auto-generated method stub
        Map<String, Object> map = new HashMap<String, Object>();

        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        info.setGoodUserId(userInfo==null?null:userInfo.getId());

        List<QuestionCommentDto> list = new ArrayList<QuestionCommentDto>();
        //查询最新的提问
        if (info.getSortType() == null) {
            info.setSortType("new");
        }
        List<QuestionCommentDto> listQuestion =  questionInfoDao.queryNewQuestion(info);
        //查询最新的回答
        List<QuestionCommentDto> listTextComent = questionCommentDao.quesyNewTextComment(info);
        List<QuestionCommentDto> listRecordComments = questionCommentDao.quesyNewRecordComment(info);

        list.addAll(listRecordComments);
        list.addAll(listQuestion);
        list.addAll(listTextComent);
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());
        dealListenAuth(info, list, userMemberInfo);
        QuestionCommentDtoComparator comparator = new QuestionCommentDtoComparator();
		Collections.sort(list, comparator);

        if(listQuestion != null && listQuestion.size()>0 ){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("er_msg", "无数据");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object queryIntelligent(QuestionInfo info) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
		List<QuestionInfo> list = questionInfoDao.queryIntelligent(info);
		if(list != null && list.size()>0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("er_msg", "无数据");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object exportExl(QuestionInfo info, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<QuestionInfo> dataset = questionInfoDao.selectQuestionListPage(info);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		String desc = "";
		String reg = "</?[^<]+>";
		//将问题描述中的html标签过滤掉
		for (QuestionInfo questionInfo : dataset) {
			if (StringUtils.isNotBlank(questionInfo.getQuestionDesc())) {
				desc = questionInfo.getQuestionDesc().replaceAll(reg, "");
				questionInfo.setQuestionDesc(desc);
			}
		}
		try {
			ExcelUtil.writeExcel(response, "问题"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, QuestionInfo.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

    private void dealListenAuth(QuestionInfo info, List<QuestionCommentDto> listRecordComments, UserMemberInfo userMemberInfo) {
        //处理语音权限
        ListIterator<QuestionCommentDto> questionCommentListIterator = listRecordComments.listIterator();
        while (questionCommentListIterator.hasNext()) {
            QuestionCommentDto next = questionCommentListIterator.next();
            if (next.getIsNeedPrivilege() != null && next.getIsNeedPrivilege().equals(1)) {
                //语音提问
                if (next.getCommentTimeOut() == 0) {
                    //免费三小时
                    next.setStatus(0);
                } else if ((info.getGoodUserId() != null) && (info.getGoodUserId().equals(next.getUserId()) || info.getGoodUserId().equals(next.getCommenterId()))) {
                    next.setStatus(1);//导师判断,回答人和当前用户一直就是受益人
                }else if(userMemberInfo != null){
                	next.setStatus(4);//会员状态
                } else if (next.getUbpId() != null) {
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(2);
                } else {
                    //订单没有支付
                    next.setStatus(3);
                }
            }
        }
    }

    @Override
    public Object queryDynamicPageByInfo(QuestionInfo info, QuestionComment comment, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户信息不存在");
//            return map;
//        } else 
        if (userInfo != null && userInfo.getId().equals(info.getUserId())) {
            info.setIsAnonymous(null);
        } else {
            info.setIsAnonymous(1);
        }
        info.setGoodUserId(userInfo==null?null:userInfo.getId());
        comment.setGoodUserId(userInfo==null?null:userInfo.getId());
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());

        info.setQuestionTime(new Timestamp(System.currentTimeMillis()));

        List<QuestionCommentDto> list = questionInfoDao.queryDynamicPageByInfo(info);
        dealListenAuth(info, list, userMemberInfo);

        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object getPageSearchQuestionByContent(QuestionInfo info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (userInfo == null) {
            map.put("err_code", -1);
            map.put("err_msg", "用户信息不存在");
            return map;
        }
        info.setGoodUserId(userInfo.getId());
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo.getId());
        Map result = questionInfoDao.countSearchQuestionByContent(info);
        Object count = result.get("count");
        if (count == null) {
            map.put("err_msg", "error");
            return map;
        }
        int total = Integer.parseInt(count.toString());
        if (total > 0) {
            List<QuestionCommentDto> list = questionInfoDao.getPageSearchQuestionByContent(info);
            dealListenAuth(info, list, userMemberInfo);
            map.put("rows", list);
        }
        map.put("total", total);
        return map;
    }

    @Override
    public Object queryUserDynamicPageByInfo(QuestionInfo info, QuestionComment comment, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户信息不存在");
//            return map;
//        } else 
        if (userInfo != null && userInfo.getId().equals(info.getUserId())) {
            info.setIsAnonymous(null);
        } else {
            info.setIsAnonymous(1);
        }
        
        
        
        info.setGoodUserId(userInfo==null?null:userInfo.getId());
        comment.setGoodUserId(userInfo==null?null:userInfo.getId());
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());
        List<QuestionCommentDto> list = questionInfoDao.queryUserDynamicPageByInfo(info);
        int total = questionInfoDao.countUserDynamicPageByInfo(info);

        dealListenAuth(info, list, userMemberInfo);

        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        map.put("total", total);
        return map;
    }

    @Override
    public Object queryTopicPageByInfo(QuestionInfo info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户信息不存在");
//            return map;
//        } else 
        if (userInfo != null && userInfo.getId().equals(info.getUserId())) {
            info.setIsAnonymous(null);
        } else {
            info.setIsAnonymous(1);
        }
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());
        info.setGoodUserId(userInfo==null?null:userInfo.getId());
        info.setQuestionTime(new Timestamp(System.currentTimeMillis()));

        List<QuestionCommentDto> list = questionInfoDao.queryTopicPageByInfo(info);

        dealListenAuth(info, list, userMemberInfo);

        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object queryTopicIntelligent(QuestionInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<QuestionInfo> list = questionInfoDao.queryTopicIntelligent(info);
        if (list != null && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("er_msg", "无数据");
            map.put("rows", list);
        }
        return map;
    }


    @Override
    public Object relatedQuestions(QuestionInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<QuestionInfo> list = questionInfoDao.relatedQuestions(info);
        if (list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询无数据");
        }
        return map;
    }

	@Override
	public Object miniMyQAQ(MiniMyQAQDTO info) {
		Map<String, Object> map = new HashMap<String, Object>();
        List<MiniMyQAQDTO> list = questionInfoDao.miniMyQAQ(info);
        if (list.size() > 0) {
            map.put("err_code", "200");
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", "400");
            map.put("err_msg", "查询无数据");
            map.put("rows", null);
        }
        return map;
	}

	@Override
	public Object queryPostPage(QuestionInfo info, HttpSession session) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			return ResultUtil.error(ResultEnum.NOT_LOGIN);
		}
		info.setUserId(loginUser.getId());
		return ResultUtil.success(questionInfoDao.queryPostPage(info));
	}

	@Override
	public Object latestByTypes(Integer[] types) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null != types){
			List<QuestionInfoDTO> list = questionInfoDao.latestByTypes(types);
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
			}else{
				map.put("err_code", -1);
				map.put("err_msg", "无数据");
				map.put("rows", list);
			}
			return map;
			
		}else{
			map.put("err_code", -2);
			map.put("err_msg", "请求参数错误");
			return map;
		}
	}
}
